package edu.wright.ceg4980.year2013.keyboard;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.LinkedList;

public class TimedPasswordFile {
	
	private String fileName;
	
	private String userName;
	
	private char[] password;
	
	private int[] featureLengths;

	private boolean isReady;
	
	private int oldestHistoryEntry;
	
	private int historyLimit;
	
	private long historyMetadataPos;
	
	private long historyStartPos;
	
	
	
	private TimedPasswordFile() { }
	
	/**
	 * Creates a binary file storing data for the keyboard dynamics software. Allocating the file before writing actual data allows
	 * the file to be only partially completed, so that a user is not forced to go through an explicit training phase. The file is
	 * in binary format so that it can be updated without having to wipe the entire file.
	 * 
	 * The data file is organized into a header block and data block. The header contains the following information in this order.
	 *  - Null-terminated user name, in plain ASCII
	 *  - Null-terminated user password, in plain ASCII
	 *  - Single integer containing the ready state of the training data (1 if the user is fully trained, 0 if they are not)
	 *  - Single integer pointing to the oldest history entry
	 *  - Single integer containing the maximum history size
	 *  - Single integer 'n' containing the number of features stored for the user
	 *  - 'n' more integers, containing the number length of each feature
	 * 
	 * From the current history size and maximum history size, we can determine whether or not the keyboard dynamics detector is fully trained and ready to use.
	 * 
	 * The header is immediately followed by the training data. The training data is organized as:
	 *    (h_1, f_1), (h_1, f_2), ..., (h_1, f_n), (h_2, f_1), (h_2, f_2), ... (h_max, f_n)
	 *  
	 *  Note that all integers are 4 bytes long and all longs are 8 bytes long.
	 * 
	 * @param fileName Name of the file to create
	 * @param userName User's username
	 * @param password User's password
	 * @param featureLengths The length of each feature; for example, a keydown-to-keydown feature would have a length of password.length() - 1.
	 *                       The total number of features stored for the user is determined by the length of this array.
	 * @param historyLimit The number of trials that should be stored for the user
	 * 
	 * @throws IOException
	 */
	public static TimedPasswordFile allocate(String fileName, String userName, char[] password, int[] featureLengths, int historyLimit) throws IOException {
		TimedPasswordFile file = new TimedPasswordFile();
		file.fileName = fileName;
		file.userName = userName;
		file.password = new char[password.length];
		System.arraycopy(password, 0, file.password, 0, password.length);
		file.featureLengths = new int[featureLengths.length];
		System.arraycopy(featureLengths, 0, file.featureLengths, 0, featureLengths.length);
		file.isReady = false;
		file.oldestHistoryEntry = 0;
		file.historyLimit = historyLimit;
		file.historyMetadataPos = (userName.length() + 1) + (password.length + 1);
		
		RandomAccessFile f = new RandomAccessFile(fileName, "rw");
		// allocate storage for username and password (with null terminator)
		int fileLengthBytes = (userName.length() + 1) + (password.length + 1);
		// allocate storage for the training ready flag, history limit, current history pointer (3 integers, 4 bytes each)
		fileLengthBytes += 12;
		// allocate storage for feature vector information
		fileLengthBytes += 4 + 4 * featureLengths.length;
		// allocate storage for all feature data (8 bytes per long)
		for (int i = 0; i < featureLengths.length; ++i) {
			fileLengthBytes += featureLengths[i] * historyLimit * 8;
		}
		
		f.setLength(fileLengthBytes);

		// write null terminated user name
		f.writeBytes(userName);
		f.writeByte('\0');
		
		// write password
		for (char c : password) {
			f.writeByte(c);
		}
		f.writeByte('\0');
		
		// write training data ready flag
		f.writeInt(0);
		
		// write current history pointer
		f.writeInt(0);
		
		// write history size limit
		f.writeInt(historyLimit);
		
		// write number of features and length of each feature
		f.writeInt(featureLengths.length);
		for (int i = 0; i < featureLengths.length; ++i) {
			f.writeInt(featureLengths[i]);
		}
		
		file.historyStartPos = f.getFilePointer();
		
		f.close();
		
		return file;
	}
	
	public static TimedPasswordFile read(String fileName) throws IOException {
		TimedPasswordFile file = new TimedPasswordFile();
		file.fileName = fileName;
		
		RandomAccessFile f = new RandomAccessFile(fileName, "r");

		file.userName = new String(readCharString(f));
		file.password = readCharString(f);
		
		file.historyMetadataPos = f.getFilePointer();
		file.isReady = (f.readInt() == 1);
		file.oldestHistoryEntry = f.readInt();
		file.historyLimit = f.readInt();

		file.featureLengths = new int[f.readInt()];
		for (int i = 0; i < file.featureLengths.length; ++i) {
			file.featureLengths[i] = f.readInt();
		}
		
		file.historyStartPos = f.getFilePointer();
		
		f.close();

		return file;
	}
	
	private static char[] readCharString(RandomAccessFile f) throws IOException {
		LinkedList<Character> stringList = new LinkedList<Character>();
		{
			char c;
			while ((c = (char) f.readByte()) != '\0') {
				stringList.add(c);
			}
		}
		
		char[] stringArray = new char[stringList.size()];
		int i = 0;
		for (char c : stringList) {
			stringArray[i] = c;
			++i;
		}
		
		return stringArray;
	}
	
	public boolean isReady() {
		return isReady;
	}
	
	public String getUserName() {
		return userName;
	}
	
	public char[] getPassword() {
		return password;
	}
	
	public ArrayList<long[][]> readAllData() throws IOException {
		RandomAccessFile file = new RandomAccessFile(fileName, "r");

		file.seek(historyStartPos);
		
		ArrayList<long[][]> data = new ArrayList<long[][]>(this.historyLimit);
		for (int h = 0; h < this.historyLimit; ++h) {
			long[][] historyEntry = new long[featureLengths.length][0];
			for (int f = 0; f < historyEntry.length; ++f) {
				historyEntry[f] = new long[featureLengths[f]];
				for (int i = 0; i < historyEntry[f].length; ++i) {
					historyEntry[f][i] = file.readLong();
				}
			}
			data.add(historyEntry);
		}
		
		file.close();
		
		return data;
	}
	
	/**
	 * Write a single history entry for a user into an existing keyboard dynamics file.
	 */
	public void writeKeyData(long[][] data) throws IOException {
		RandomAccessFile file = new RandomAccessFile(fileName, "rw");

		int historyEntrySize = 0;
		for (int i : featureLengths) {
			historyEntrySize += i * 8;
		}
		
		// write out the fresh data
		file.seek(historyStartPos + oldestHistoryEntry * historyEntrySize);
		for (int f = 0; f < data.length; ++f) {
			for (long i : data[f]) {
				file.writeLong(i);
			}
		}

		oldestHistoryEntry = (oldestHistoryEntry + 1) % historyLimit;
		if (!isReady && oldestHistoryEntry == 0) {
		// if training data changed from not ready to ready, write this fact to the file
			file.seek(historyMetadataPos);
			isReady = true;
			file.writeInt(1);
		} else {
			file.seek(historyMetadataPos + 4);
		}
		
		// write out the new history size
		file.writeInt(oldestHistoryEntry);
		
		file.close();
	}
}
